package com.tim.file;

import com.tim.controller.BaseContoller;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ImportResource;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

@ImportResource(value = {
        "classpath*:spring-bean.xml"
})
@RestController
@SpringBootApplication
@Api(value = "响应自定义", tags = "响应自定义")
@EnableAsync
@EnableScheduling
public class TimPoiApplication extends BaseContoller {
    @Value("${blog.sqlite.url}")
    String sqlLiteUrl;
    String initTable = "CREATE TABLE IF NOT EXISTS `sys_t_sql` (`ID` varchar(50) NOT NULL,  `GROUPS` varchar(50) NOT NULL,  `CODES` varchar(50) NOT NULL ,  `SQL_CONTENT` text NOT NULL ,  `PARAM_KEYS` varchar(3000) DEFAULT NULL,  `DES` varchar(400) DEFAULT NULL ,  `TAL` varchar(255) DEFAULT NULL ,  `C_TIME` datetime NOT NULL ,  `C_CREATOR` varchar(50) NOT NULL ,  PRIMARY KEY (`ID`))";

    public static void main(String[] args) {
        SpringApplication.run(TimPoiApplication.class, args);
    }

    @Bean(name = "sqlLiteSql")
    public Statement initSqlBean() throws ClassNotFoundException {
        System.out.println("=========init========");
        Class.forName("org.sqlite.JDBC");
        Connection connection = null;
        Statement statement = null;
        try {
            connection = DriverManager.getConnection(sqlLiteUrl);
            statement = connection.createStatement();
            statement.setQueryTimeout(30);
            statement.execute(initTable);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println(e.getMessage());
        }
        return statement;
    }

    /**
     * 跨域过滤器
     *
     * @return
     */
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
    }

}
